<?php
namespace app\admin\controller; 
use think\AjaxPage;
use think\Controller;
use think\Url;
use think\Config;
use think\Page;
use think\Verify;
use think\Db;
class Storebossinfo extends Base {
	
	public function baseinfo(){
		echo '敬请期待';
	}
	
	public function userlist(){
		 return $this->fetch();
	}
	
	public function ajaxuser(){
		$storeid = session('store_id');
		
        $where = " storeid= $storeid "; // 搜索条件                
		
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and username like '%$key_word%'" ;
        }
        
		$where = "$where and ml_userinfo.unionid = ml_userinfo_p.unionid";
		
        $countres = Db::query("select count(userid) from ml_userinfo,ml_userinfo_p where $where");
		$count = $countres[0]['count(userid)'];
        //M('userinfo,userinfo_p')->where($where)->count();
        $Page  = new AjaxPage($count,10);

        $show = $Page->show();
		
		if(I('orderby1')!=''){
			$order_str = "{$_POST['orderby1']} {$_POST['orderby2']}";
		}
		else{
			$order_str = "userid desc";
		}
        
        $goodsList = Db::query("select * from ml_userinfo,ml_userinfo_p where $where order by $order_str limit $Page->firstRow,$Page->listRows");
        //M('userinfo')->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();


        $this->assign('userlist',$goodsList);
		$this->assign('rtype',config('RoleType'));
        $this->assign('page',$show);// 赋值分页输出       
        return $this->fetch();
	}
	
	public function transferuser(){
		$storeid = session('store_id');
		$userid = input('userid/d',0);
		$uname = input('uname/s','');
        $where = ['storeid'=>$storeid,'role'=>2];
        
        $uList = M('userinfo')->where($where)->where('userid','<>',$userid)->select();
        $this->assign('rtype',config('RoleType'));
		$this->assign('ulist',$uList);
		$this->assign('userid',$userid);
		$this->assign('uname',$uname);
		return $this->fetch();
	}
	
	public function transfer(){
		$userid = input('uid/d',0);
		$tuid = input('tuid/d',0);
		
		$uresult = Db::query("select role,userid,accounts,username from ml_userinfo,ml_userinfo_p where ml_userinfo.unionid = ml_userinfo_p.unionid and userid=?",array($userid));
		$turesult = Db::query("select role,userid,username from ml_userinfo,ml_userinfo_p where ml_userinfo.unionid = ml_userinfo_p.unionid and where userid=?",array($tuid));
		
		$urole = $uresult[0]['role'];
		$turole = $turesult[0]['role'];
		$useraccounts = $uresult[0]['accounts'];
		$username = $uresult[0]['username'];
		$tname = $turesult[0]['username'];
		if($useraccounts>0){
			$this->ajaxReturn(['status' => -1,'msg' => $username .'的账号还有 '.$useraccounts.' 余额,请先提现!']);
		}
		
		$boss = config('BOSS');
		$user = config('USER');
		
		if($urole !=$boss || $turole!=$boss){
			$this->ajaxReturn(['status' => -1,'msg' => '角色信息错误']);
		}
		
		if($urole != $turole){
			$this->ajaxReturn(['status' => -1,'msg' => '角色信息错误..']);
		}
		
		$unum = Db::query("update ml_clientslist set belongto = ? where belongto = ?",array($tuid,$userid));		
		adminLog('转移用户 '.$userid.' 到  '.$tuid);		
		$this->ajaxReturn(['status' => 1,'msg' => '转移成功']);
	}
	
	//用户角色编辑
	public function useredit(){
		$userid = input('userid/d',0);		
		if ((I('is_ajax') == 1) && IS_POST) {
			
			if($userid<=0){
				$this->returnMsg('-1','userid 错误');
			}
			
			$data = input('post.');
			
			$torole = $data['role'];
			$savedata['role'] = $data['role'];
			
			//获得当前用户角色信息
			$userinfo = Db::name('userinfo')->where(['userid'=>$userid])->field('userid,role,accounts')->select();
			if(count($userinfo)<=0){
				$this->ajaxReturn(['status' => -1,'msg' => '用户信息不存在']);
			}
			
			$curRole = $userinfo[0]['role'];
			$curaccounts = $userinfo[0]['accounts'];
			//角色相同不处理			
			if($curRole == $torole){
				$this->ajaxReturn(['status' => 1,'msg' => '操作成功','url'=>U("Admin/Storebossinfo/userlist")]);
			}
			
			//店家变普通客户
			if($torole == '1' && $curRole=='2'){
				
				if($curaccounts>0){
					$this->ajaxReturn(['status' => 0,'msg' => '商家还有余额，请先提现哦。']);
				}
				
				$curRoleDb = Db::name('userinfo')->where(['role'=>$torole])->field('userid,role')->select();
				$clientNum = Db::name('clientslist')->where(['belongto'=>$userid])->count();
				if(count($curRoleDb>0) && $clientNum>0){
					$this->ajaxReturn(['status' => 0,'msg' => '已有客户绑定了该店家,请先解除他们的关系']);
//					$this->error('已有客户绑定了该店家,请先解除他们的关系');
				}
			}
			
			if($torole == '2'){
				/*$storeid = session('store_id');
				$bossRes = Db::name('userinfo')->where(['role'=>$torole,'storeid'=>$storeid])->select();
				if(count($bossRes) >0){
					$this->ajaxReturn(['status' => 0,'msg' => '已经绑定了一个店家']);
				}*/
			}
			
			Db::name('userinfo')->where(['userid'=>$userid])->save($savedata);
			$this->ajaxReturn(['status' => 1,'msg' => '操作成功','url'=>U("Admin/Storebossinfo/userlist")]);
		}
		
//		$infos = Db::name('userinfo')->where(['userid'=>$userid])->field('userid,username,role')->find();
			
		$infos = Db::view('userinfo','userid,role')
	    ->view('userinfo_p','username','userinfo.unionid=userinfo_p.unionid')
	    ->where(['userid'=>$userid])
	    ->select();
		
		$roletype = userroleArr();
		
		$this->assign('info',$infos[0]);// 赋值分页输出
		$this->assign('rtype',$roletype);
        return $this->fetch();
	}

	//客户列表
	public function userclient(){
		$userid = input('userid/d',0);
		
		$endpage = config('PageSize');
		$count = Db::name('clientslist')->where(['belongto'=>$userid])->count();
        $Page  = new AjaxPage($count,$endpage);
		
		$uresult = Db::view('clientslist','*')
	    ->view('userinfo','userid,role','userinfo.userid=clientslist.clientid')
		->view('userinfo_p','username,phone','userinfo.unionid=userinfo_p.unionid')
	    ->where(['clientslist.belongto'=>$userid])
		->limit($Page->firstRow,$Page->listRows)
	    ->select();
		
		$show = $Page->show();		
		
//		exit(json_encode($uresult));
		
		$this->assign('ulist',$uresult);// 赋值分页输出
		$this->assign('count',$count);
		$this->assign('page',$show);
        return $this->fetch();
	}
	
	
	
	public function uselist(){
		$begin = date('Y-m-d',strtotime("-1 year"));//30天前
    	$end = date('Y/m/d',strtotime('+1 days')); 	
    	$this->assign('timegap',$begin.'-'.$end);
        return $this->fetch();
	}
	
	
	
	//收支明细
	public function useajax(){

		
		
		$orderby1 = input('orderby1');
		$orderby2 = input('orderby2');
		
		$storeid = session('store_id');
		
        $where = " and ml_goodsuse.storeid= $storeid "; // 搜索条件    
		
		$key_word = I('key_word') ? trim(I('key_word')) : '';
		
        if($key_word)
        {
            $where .= " and gname like '%$key_word%'" ;
        }
		
		
		$begin = strtotime(I('add_time_begin'));
        $end = strtotime(I('add_time_end'));
		if(!empty($begin)&&!empty($end)){
			$where .= " and ml_goodsuse.usetime between $begin and $end ";
		}
		
		$count = Db::query("select count(ids) from ml_goodsuse,ml_goods 
		where ml_goodsuse.goodsid = ml_goods.id $where")[0]['count(ids)'];
		
		//exit('$ulens=....$count='.$count.'..$where..'.$where);
		
		$endpage = config('PageSize');
        $Page  = new AjaxPage($count,$endpage);

		$uresult = Db::query("select ml_goodsuse.*,ml_goods.gname from ml_goodsuse,ml_goods where ml_goodsuse.goodsid = ml_goods.id $where order by $orderby1 $orderby2 limit ?,?",[$Page->firstRow,$Page->listRows]);
		
		$ulens = count($uresult);
		
		//exit('$ulens='+json_encode($uresult));
		
		$uarr = array();
		for($i=0;$i<$ulens;$i++){			
			$bossid = $uresult[$i]["bossid"];
			$userid = $uresult[$i]["userid"];			
			
			if(!in_array($bossid,$uarr)){
				array_push($uarr,$bossid);
			}
			
			if(!in_array($userid,$uarr)){
				array_push($uarr,$userid);
			}			
		}
		
		if(count($uarr)>0){
			$userstr = implode(",",$uarr);		
			$userarr = Db::query("select userid,username from ml_userinfo,ml_userinfo_p where ml_userinfo_p.unionid = ml_userinfo.unionid and userid in (".$userstr.")");
			$userNameCount = count($userarr);
			$userNameArr = array();
			for($i=0;$i<$userNameCount;$i++){
				$userNameArr[$userarr[$i]['userid']] = $userarr[$i]['username'];
			}
			
			for($i=0;$i<$ulens;$i++){
				
				$bossid = $uresult[$i]["bossid"];
				$userid = $uresult[$i]["userid"];
				
				$uresult[$i]["bossname"] = $userNameArr[$bossid];
				$uresult[$i]["username"] = $userNameArr[$userid];
			}
		}
		
		$show = $Page->show();		
		$this->assign('ulist',$uresult);
        $this->assign('page',$show);// 赋值分页输出
        return $this->fetch();
	}
	
	//使用详情
	public function uselistMsg(){
		
		$useid = input('id/d',-1);

		$uresult = Db::view('goodsusemsg','*')
	    ->view('userinfo','role','userinfo.userid=goodsusemsg.userid')
		->view('userinfo_p','username,phone','userinfo_p.unionid = userinfo.unionid')
	    ->where(['goodsusemsg.useid'=>$useid])
	    ->select();
		
		$rolename = C('Roles');
		$states = C('WithDrawState');
		
		foreach($uresult as $key=>$value){
			$uresult[$key]['rolename'] = $rolename[$value['role']];
			$uresult[$key]['wstate'] = $states[$value['usetype']];		
		}
		
		$this->assign('ulist',$uresult);
		return $this->fetch();
	}
	
	
	public function getindex(){
        return $this->fetch();
	}
	
	//提现记录
	public function getajaxlist(){
		
		$page = input('p/d',0);
		$endpage = config('PageSize');
		
		$orderby1 = input('orderby1');
		$orderby2 = input('orderby2');
		
		$storeid = session('store_id');
		
        $where = " where storeid= $storeid and usetype=3 "; // 搜索条件    
		$key_word = I('key_word') ? trim(I('key_word')) : '';
		
        if($key_word)
        {
            $where .= " and clientname like '%$key_word%'" ;
        }
		
		
		$begin = strtotime(I('add_time_begin'));
        $end = strtotime(I('add_time_end'));
		if(!empty($begin)&&!empty($end)){
			$where .= " and opdate between $begin and $end ";
		}

		$count = Db::query("select count(ids) from ml_userconsume $where")[0]['count(ids)'];
		
        $Page  = new AjaxPage($count,$endpage);
		
		$result = Db::query("select * from ml_userconsume $where order by $orderby1 $orderby2 LIMIT ?,?",[$Page->firstRow,$Page->listRows]);
		
		$show = $Page->show();
				
		$this->assign('ulist',$result);
        $this->assign('page',$show);
        return $this->fetch();		
	}
	
	public function withdrawlist(){
		return $this->fetch();
	}
	
	public function withdrawajax(){		
		
		$page = input('p/d',0);
		$endpage = config('PageSize');
		
		$orderby1 = input('orderby1');
		$orderby2 = input('orderby2');
		
		$storeid = session('store_id');
		
        $where = " and ml_withdrawlist.storeid= $storeid"; // 搜索条件    
		$key_word = I('key_word') ? trim(I('key_word')) : '';
		
        if($key_word)
        {
            $where .= " and ml_userinfo_p.username like '%$key_word%'" ;
        }
		
		$where .=" and ml_userinfo_p.unionid = ml_userinfo.unionid ";
		
		$begin = strtotime(I('add_time_begin'));
        $end = strtotime(I('add_time_end'));
		if(!empty($begin)&&!empty($end)){
			$where .= " and ml_withdrawlist.drawdate between $begin and $end ";
		}
		
		$count = Db::query("select count(drawid) from ml_withdrawlist,ml_userinfo,ml_userinfo_p 
		where ml_withdrawlist.userid=ml_userinfo.userid $where")[0]['count(drawid)'];
        $Page  = new AjaxPage($count,$endpage);
		
		$uresult = Db::query("select ml_userinfo.userid,username,role,phone,
		drawid,drawdate,sum,status from ml_withdrawlist,ml_userinfo,ml_userinfo_p where ml_withdrawlist.userid=ml_userinfo.userid $where ORDER BY $orderby1 $orderby2 LIMIT ?,?",
		[$Page->firstRow,$Page->listRows]);
		
		$rolename = C('Roles');
		foreach($uresult as $key=>$value){
			$uresult[$key]['rolename'] = $rolename[$value['role']];
		}
		
		$show = $Page->show();
				
		$this->assign('ulist',$uresult);
        $this->assign('page',$show);
        return $this->fetch();
	}
	
	public function withdrawfun(){
		//return $this->fetch();
		$drawid = input('ids/d',0);
		
		$drawinfo = Db::name("withdrawlist")->where(['drawid'=>$drawid])->select();
		if(count($drawinfo)<=0){
			$this->ajaxReturn(['status' => 0,'msg' => '错误的提现数据']);
		}
		
		$userid = $drawinfo[0]['userid'];
		$userresult = Db::query("select accounts,extrapwd,openid,storeid,unionid from ml_userinfo where userid = $userid");
		if($userresult==null||count($userresult)<=0){
			$this->ajaxReturn(['status' => 0,'msg' => '用户信息不存在']);
		}
		
		$unionid = $userresult[0]['unionid'];
		$userresult_p = Db::query("select * from ml_userinfo_p where unionid = '$unionid'");
		if(count($userresult)<=0){
			$this->ajaxReturn(['status' => 0,'msg' => '用户信息不存在..']);
		}
		
		$account = $userresult[0]['accounts'];		
		$money = $drawinfo[0]['sum'];
		$openid = $drawinfo[0]['openid'];
		$appid = $drawinfo[0]['appid'];	
		$username = $userresult_p[0]['username'];
		$getmoney = $money*100;
		$storeid = $drawinfo[0]['storeid'];
		
		if($account < $money){
			$this->ajaxReturn(['status' => 0,'msg' => '用户当前余额不足']);
		}
		
		
		$tdata=array(
			'openid'=>$openid,//openid
			'check_name'=>'NO_CHECK',//是否验证真实姓名参数
			're_user_name'=>$username,//姓名
			'amount'=>$getmoney,//最小1元 也就是100
			'desc'=>"爱梨后台提现通知"//描述
		);
		
		$pay_code = 'miniAppPay';     
		include_once  "plugins/payment/weixin/weixin.class.php";
        $code = '\\weixin';
        $payment = new $code();
		$drawstate = $payment->transfer($tdata,$appid);
		if($drawstate == "SUCCESS"){
			$sum = $account-$money;
			$moneyval = (-1)*$money;
			db('withdrawlist')->delete(['drawid'=>$drawid]);
			db('userinfo')->where(['userid'=>$userid])->save(['accounts'=>$sum]);
			db('userconsume')->add(['usetype'=>3,'userid'=>$userid,'nums'=>$moneyval,'opdate'=>time(),'storeid'=>$storeid,'clientname'=>$username,'remark'=>'后台转账']);				
			$this->ajaxReturn(['status' => 1,'msg' => '提现成功']);
		}
		else if($drawstate == 'NOTENOUGH'){
			//余额不足。请稍等后台审核
			$this->ajaxReturn(['status' => 0,'msg' => '平台余额不足']);
		}
		else{
			$this->ajaxReturn(['status' => 0,'msg' => '提现失败：'.$drawstate]);
		}	
	}
	
	public function buylist(){
		$paystate = config('PAYSTATE');
		$parr = [];
		array_push($parr,['id'=>-1,'v'=>'全部']);
		foreach($paystate as $key=>$value){
			array_push($parr,['id'=>$key,'v'=>$value]);
		}
		$this->assign('pstate',$parr);
		return $this->fetch();
	}
	
	//购买记录
	public function buylistajax(){
		
		$endpage = config('PageSize');
		
		$orderby1 = input('orderby1');
		$orderby2 = input('orderby2');
		$paystate = input('paystate/d',0);
		//商品类型		
		$goodstype = input('goodstype/d',0);
		
		$storeid = session('store_id');		
        $where = " and b.storeid = $storeid"; // 搜索条件    
		$key_word = I('key_word') ? trim(I('key_word')) : '';
		
        if($key_word)
        {
            $where .= " and b.setsname like '%$key_word%'" ;
        }
		
		if($goodstype > 0){
			$where .= " and g.type = $goodstype ";
		}
		
		$begin = strtotime(I('add_time_begin'));
        $end = strtotime(I('add_time_end'));
		
		if(empty($begin) || empty($end)){
			$begin = time()-(24*60*60*30);
			$end = time()+(24*60*60);
		}
		$where .= " and b.buydate between $begin and $end ";
		if($paystate>=0){
			$where .= " and paystate = $paystate ";
		}
		
		$selectSql = "select b.*,ml_userinfo_p.username,ml_userinfo_p.phone from ml_buylist as b, ml_userinfo as u,ml_goods as g,ml_userinfo_p 
		where b.userid = u.userid and ml_userinfo_p.unionid = u.unionid and g.id = b.goodsid $where ";		
		$sqlOrder = " order by $orderby1 $orderby2 LIMIT ?,?";	
		
		$count = Db::query("select count(buyid) from ml_buylist as b,ml_goods as g where buyid >0 and g.id = b.goodsid $where")[0]['count(buyid)'];
        $Page  = new AjaxPage($count,$endpage);
		
		$bresult = Db::query($selectSql.$sqlOrder,[$Page->firstRow,$Page->listRows]);
		
		$show = $Page->show();
		
		$this->assign('blist',$bresult);
        $this->assign('page',$show);
		$this->assign('pstate',config('PAYSTATE'));
		$this->assign('ostate',config('ORDERSTATE'));
		
        return $this->fetch();		
	}
}

?>